package com.zerotwo.exam.center.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zerotwo.exam.center.enums.DefaultQuestionRuleEnum;
import com.zerotwo.exam.center.enums.QuestionTypeEnum;
import com.zerotwo.exam.center.mapper.QuestionMapper;
import com.zerotwo.exam.center.mapper.QuestionsMapper;
import com.zerotwo.exam.center.model.Question;
import com.zerotwo.exam.center.model.QuestionItem;
import com.zerotwo.exam.center.model.Questions;
import com.zerotwo.exam.center.service.impl.QuestionServiceImpl;
import com.zerotwo.exam.center.utils.ImportExcel;
import com.zerotwo.exam.center.utils.InOutExcel;
import com.zerotwo.exam.center.utils.ParseQuestionText;
import com.zerotwo.exam.center.model.ParseQuestionRules;
import com.zerotwo.exam.center.vo.BatchQuestion;
import com.zerotwo.exam.center.vo.ParseQuestionVo;
import com.zerotwo.exam.center.vo.QuestionInfoVo;
import com.zerotwo.exam.common.core.result.PageResult;
import com.zerotwo.exam.common.core.result.Result;
import com.zerotwo.exam.common.core.result.ResultCode;
import com.zerotwo.exam.user.feign.CourseClient;
import com.zerotwo.exam.user.model.Courses;
import com.zerotwo.exam.user.model.JoinClass;
import com.zerotwo.exam.web.utils.UserAuthUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.unit.DataSize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.swing.text.html.ImageView;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 02
 * @version 1.0
 * @Date 2024/7/5
 * @Description 题目信息
 * 规定：所有类型题目至少要有一下选项，如主观题，就算没有答案，都要给一个选项
 */
@Slf4j
@Validated
@Tag(name = "题目管理")
@RestController
@RequestMapping("/question")
@CrossOrigin
public class QuestionController {
    public static final String 创建时间 = "创建时间";
    @Autowired
    QuestionServiceImpl questionService;
    @Autowired
    CourseClient courseClient;
    @Autowired
    InOutExcel inOutExcel;
    @Autowired
    ImportExcel importExcel;
    @Autowired
    QuestionsMapper questionsMapper;
    @Autowired
    QuestionMapper questionMapper;
    @Operation(summary = "创建题目")
    @PostMapping("/add")
    public Result add(@RequestBody @Validated QuestionInfoVo questionInfo){
        //判断课程是不是自己的
        Courses course = courseClient.findCourse(questionInfo.getCourseId());
        Integer userId = UserAuthUtil.getUserId();
        if(course==null||course.getUserId()!=userId){
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        questionInfo.setTeacherId(userId);
        questionInfo.setId(null);
        String result = questionService.addQuestion(questionInfo);
        if("".equals(result)){
            return Result.msgSuccess("创建题目成功");
        }else{
            return Result.msgError(result);
        }
    }

    //测试
    @GetMapping("/excel")
    public List<Question> select(){
        //查询所有的题目
        return questionMapper.exportExcel();
    }

    @Operation(summary = "导出题目")
    @PostMapping("/exportExcel")
    public String exportExcel(HttpServletResponse response) throws IOException {
        //查询所有的题目
        List<Question> list = questionMapper.exportExcel();
        if (list!=null){
            inOutExcel.exportExcel(list, response);
        }
        return "导出成功";
    }

    @Operation(summary = "导入题目")
    @PostMapping("/importExcel")
    public String importExcel(@RequestPart("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return "文件不能为空";
        }
        // 检查文件类型，只允许Excel文件
        String contentType = file.getContentType();
        if (!contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
            return "只允许上传Excel文件";
        }
        try {
            List<Question> questionsList = importExcel.importExcel(file);
            for (Question question : questionsList) {
                if (question != null) {
                    // 清除ID值
                    question.setId(null);
                    // 如果question的type字段为null，赋予默认值0
                    if (question.getType() == null || question.getType().equals(0)) {
                        question.setType(QuestionTypeEnum.valueOf("SIGNAL_CHOICE")); //默认值
                    }
                    // 清除ID值
                    QuestionItem questionItem = new QuestionItem();
                    questionItem.setId(null);
                    questionItem.setContent(question.getContents());
                    questionItem.setQuestionId(question.getQuestionId());
                    questionItem.setAnswer(question.getAnswer());
                    Integer insert = questionMapper.importExcel(question);
                    if (insert > 0) {
                        questionMapper.importExcels(questionItem);
                    }
                }
            }
            return "导入成功";
        } catch (IOException e) {
            e.printStackTrace();
            return HttpStatus.INTERNAL_SERVER_ERROR + "导入失败";
        }
    }
    @Operation(summary = "批量创建题目")
    @PostMapping("/batchAdd")
    public Result batchAdd(@RequestBody @Validated BatchQuestion batchQuestion){
        Courses course = courseClient.findCourse(batchQuestion.getCourseId());
        Integer userId = UserAuthUtil.getUserId();
        if(course==null||course.getUserId()!=userId){
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        List<QuestionInfoVo> list=batchQuestion.getQuestionInfos();
        List<String> result=new ArrayList<>();
        list.stream().forEach(i->{
            i.setTeacherId(userId);
            i.setTagId(batchQuestion.getTagId());
            i.setCourseId(batchQuestion.getCourseId());
            result.add( questionService.addQuestion(i));
        });
        return Result.success(result);
    }
    @Operation(summary = "获取匹配题目规则")
    @GetMapping("/rules")
    public Result rules(){
        Map<String, String> collect = Arrays.stream(DefaultQuestionRuleEnum.values()).collect(Collectors.toMap(DefaultQuestionRuleEnum::name, DefaultQuestionRuleEnum::getName));
        return Result.success(collect);
    }
    @Operation(summary = "解析题目文本")
    @PostMapping("/analyze")
    public Result analyze(@RequestBody @Validated ParseQuestionVo parseQuestionVo){
        // TODO:还是后端呢？
        ParseQuestionRules rule= DefaultQuestionRuleEnum.CHAOXING.getRule();
        if(parseQuestionVo.getCustomRule()!=null){
            rule= parseQuestionVo.getCustomRule();
        }else if(parseQuestionVo.getDefaultRule()!=null){
            rule = parseQuestionVo.getDefaultRule().getRule();
        }
        //将富文本换行改成\n
        String text= parseQuestionVo.getQuestionsText().replaceAll("<br\\/?>","\n");
        //去除富文本最外层p
        text=text.replaceAll("<p>|<\\/p>","");
        log.info("题目文本",text);
        log.info("题目文本"+text);
        return Result.success( ParseQuestionText.parse(text,rule));
    }

    @Operation(summary = "更新题目")
    @PostMapping("/update")
    public Result update(@RequestBody Question question){
        //判断题目是不是自己的
        Question qu = questionService.getById(question.getId());
        Integer userId = UserAuthUtil.getUserId();
        if(qu==null||qu.getTeacherId()!=userId){
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        question.setCourseId(null);
        question.setTeacherId(null);
        questionService.updateById(question);
        return Result.msgSuccess("更新成功");
    }
    @Operation(summary = "删除题目")
    @PostMapping("/delete/{questionId}")
    public Result delete(@PathVariable String questionId){
        //判断题目是不是自己的
        Question qu = questionService.getById(questionId);
        Integer userId = UserAuthUtil.getUserId();
        if(qu==null||qu.getTeacherId()!=userId){
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        questionService.removeById(questionId);
        return Result.msgSuccess("删除成功");
    }

//    @Operation(summary = "题目列表")
//    @GetMapping("/list/{courseId}")
//    public Result list(
//            @PathVariable Integer courseId,
//            @RequestParam Integer currentPage,
//            @RequestParam(required = false) Integer tagId){
//        Courses course = courseClient.findCourse(courseId);
//        Integer userId = UserAuthUtil.getUserId();
//        if(course==null){
//            return Result.failed(ResultCode.PARAM_ERROR);
//        }
//        // 不需要查分组是不是自己的，因为，下面查询时课程id 和分组id 同时成立才行
//        LambdaQueryWrapper<Question> queryWrapper=new LambdaQueryWrapper<>();
//        //老师
//        Map<SFunction<Question, ?>, Object> queryMap=new HashMap<>();
//        queryMap.put(Question::getTagId,tagId);
//        queryMap.put(Question::getCourseId,courseId);
//        if(course.getUserId()!=userId){
//            //1.判断是否课程班级中
//            JoinClass joinClass = courseClient.joinCourseByStuId(courseId, userId);
//            if(joinClass==null){
//                return Result.failed(ResultCode.PARAM_ERROR);
//            }
//            //TODO:判断该班级是否在考试，如果考试禁止获取
//            //2.查找有公开题目的分类
//            queryWrapper.gt(Question::getIsPublic,0);
//        }
//        queryWrapper.allEq(queryMap).orderByDesc(Question::getCreatedAt);
//        IPage<Question> page=new Page<>(currentPage,10);
//        IPage<Question> list = questionService.page(page,queryWrapper);
//        return Result.success(PageResult.setResult(list));
//    }

    @Operation(summary = "题目列表")
    @GetMapping("/list/{courseId}")
    public Result list(
            @PathVariable Integer courseId,
            @RequestParam Integer currentPage,
            @RequestParam(required = false) Integer tagId,
            @RequestParam String content){


        Courses course = courseClient.findCourse(courseId);
        Integer userId = UserAuthUtil.getUserId();
        if(course==null){
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        // 不需要查分组是不是自己的，因为，下面查询时课程id 和分组id 同时成立才行
        LambdaQueryWrapper<Question> queryWrapper=new LambdaQueryWrapper<>();
        //老师
        Map<SFunction<Question, ?>, Object> queryMap=new HashMap<>();
        queryMap.put(Question::getTagId,tagId);
        queryMap.put(Question::getCourseId,courseId);
        if(course.getUserId()!=userId){
            //1.判断是否课程班级中
            JoinClass joinClass = courseClient.joinCourseByStuId(courseId, userId);
            if(joinClass==null){
                return Result.failed(ResultCode.PARAM_ERROR);
            }
            //TODO:判断该班级是否在考试，如果考试禁止获取
            //2.查找有公开题目的分类
            queryWrapper.gt(Question::getIsPublic,0);
        }
        queryWrapper.allEq(queryMap).orderByDesc(Question::getCreatedAt);
        //查询题目
        if(StringUtils.isNotBlank(content)){
            System.out.println("content = " + content);
            queryWrapper.like(Question::getContent,content);
        }
        IPage<Question> page=new Page<>(currentPage,10);
        IPage<Question> list = questionService.page(page,queryWrapper);
        return Result.success(PageResult.setResult(list));
    }

    //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    @Operation(summary = "题目详情")
    @GetMapping("/detail/{questionId}")
    public Result<QuestionInfoVo> detail(
            @PathVariable Integer questionId){
        Question question = questionService.getById(questionId);
        Integer userId = UserAuthUtil.getUserId();
        // 是否有查看权限
        if(question.getTeacherId()!=userId){
            //1.判断是否课程班级中
            JoinClass joinClass = courseClient.joinCourseByStuId(question.getCourseId(), userId);
            if(joinClass==null){
                return Result.failed(ResultCode.PARAM_ERROR);
            }
            //TODO:判断该班级是否在考试，如果考试禁止获取

            //2.查找有公开题目的分类
        }
        QuestionInfoVo questionInfo = questionService.questionInfo(questionId);
        return Result.success(questionInfo);
    }
}
